<template>
  <div>
    <el-drawer class="drawer" title="" :visible.sync="drawer" direction="rtl">
      <div class="drawer-container" v-loading="loading" style="height:750px;overflow-y:auto;">
        <!-- 长短租订单信息 -->
        <div class="drawer-body" v-if="orderInfo && orderInfo.orderType==='1' && houseInfo">
          <div class="drawer-main" style="padding: 20px 30px;height:750px;overflow-y:auto;margin-bottom: 80px;">
            <el-tabs v-model="activeName">
              <el-tab-pane label="基本信息" name="first">
                <el-descriptions title="房屋信息" :column="1">
                  <el-descriptions-item label="名称">
                    {{ houseInfo.premisesAddress }}
                  </el-descriptions-item>
                  <el-descriptions-item label="户型">
                    {{ houseInfo.roomType }}室
                    {{ houseInfo.hall }}厅
                    {{ houseInfo.toilet }}卫
                  </el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="基础信息" :column="1">
                  <el-descriptions-item label="租住方式">
                    <dict-tag :options="dict.type.order_type" :value="orderInfo.orderType"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="状态">
                    <dict-tag :options="dict.type.order_all_state" :value="orderInfo.orderState"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="租住周期">
                    {{ orderInfo.checkInTime | formatDate('YYYY-MM-DD') }} 至
                    {{ orderInfo.checkOutTime | formatDate('YYYY-MM-DD') }}
                  </el-descriptions-item>
                  <el-descriptions-item label="来源">
                    <dict-tag :options="dict.type.order_source" :value="orderInfo.orderSource"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="成交方式">
                    <dict-tag :options="dict.type.trading_mode" :value="orderInfo.tradingMode"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="订单号">{{
                      orderInfo.orderId
                    }}
                  </el-descriptions-item>
                </el-descriptions>
                <!--个人入住信息-->
                <el-descriptions title="承租信息" :column="1"
                                 v-if="orderInfo.orderLessee&&orderInfo.orderLessee.lesseeType==='1'"
                >
                  <el-descriptions-item label="姓名">
                    {{ orderInfo.orderLessee.lesseeName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="手机号">
                    {{ orderInfo.orderLessee.phone }}
                  </el-descriptions-item>
                  <el-descriptions-item label="身份证">
                    {{ orderInfo.orderLessee.cardNumber }}
                  </el-descriptions-item>
                </el-descriptions>
                <!--企业入住信息-->
                <el-descriptions title="承租信息" :column="1"
                                 v-if="orderInfo.orderLessee&&orderInfo.orderLessee.lesseeType==='2'"
                >
                  <el-descriptions-item label="企业名称">
                    {{ orderInfo.orderLessee.enterpriseName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="统一社会信用代码">
                    {{ orderInfo.orderLessee.socialCreditCode }}
                  </el-descriptions-item>
                  <el-descriptions-item label="企业联系人">
                    {{ orderInfo.orderLessee.lesseeName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="联系人手机号">
                    {{ orderInfo.orderLessee.phone }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
              <el-tab-pane label="入住人" name="second" v-if="showMember">
                <div v-if="drawer">
                  <div class="member">
                    <div class="member-title" v-if="orderInfo.orderLessee.lesseeType ==='1'">承租人</div>
                    <div class="member-title" v-if="orderInfo.orderLessee.lesseeType ==='2'">房管员</div>
                    <div class="member-box">
                      <div>住客：{{ lessee.memberName }}<i
                        :class="lessee.sex?lessee.sex==='1'?'el-icon-male':'el-icon-female':''"
                      ></i></div>
                      <div>手机号：{{ lessee.memberPhone }}</div>
                      <div>身份证：{{ lessee.idCard }}</div>
                    </div>
                  </div>
                  <div class="member">
                    <div class="member-title">同住人</div>
                    <template v-for="(item) in list.filter(item => item.memberType !== '1')">
                      <div class="member-box" v-if="item.memberType !== '1'" :key="item.memberId">
                        <div>
                          <div>住客：{{ item.memberName }} <i
                            :class="item.sex?item.sex==='1'?'el-icon-male':'el-icon-female':''"
                          ></i></div>
                          <div>手机号：{{ item.memberPhone }}</div>
                          <div>身份证：{{ item.idCard }}</div>
                        </div>
                        <div style="margin-top: 20px">
                          <el-button size="small" @click="putMember(item)">编辑</el-button>
                          <el-button size="small" @click="delMember(item)">删除</el-button>
                        </div>
                      </div>
                    </template>
                    <template v-if="list.filter(item => item.memberType !== '1').length === 0">
                      <div class="member-box" style="text-align: center;margin-top: 20px">
                        <div>暂无人员信息</div>
                      </div>
                    </template>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!-- 空置房源信息 -->
        <div class="drawer-body" v-if="house&&!orderId">
          <div class="drawer-main" style="padding: 20px 30px;height:750px;overflow-y:auto;margin-bottom: 80px;">
            <el-tabs v-model="activeName">
              <el-tab-pane label="基本信息" name="first">
                <el-descriptions title="房屋信息" :column="1">
                  <el-descriptions-item label="名称">
                    {{ house.premisesAddress }}
                  </el-descriptions-item>
                  <el-descriptions-item label="户型">
                    {{ house.roomType }}室
                    {{ house.hall }}厅
                    {{ house.toilet }}卫
                  </el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="基础信息" :column="1">
                  <el-descriptions-item label="租住方式">
                    <dict-tag :options="dict.type.order_type" :value="orderType"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="状态">
                    空置
                  </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <div class="drawer-footer" v-if="activeName === 'first'">
        <el-row v-if="orderId">
          <!-- 订单状态:待入住 -->
          <el-col v-if="orderInfo.orderState === '1'">
            <el-button size="small" @click="handleContractInfo">合同信息</el-button>
            <el-button size="small" @click="handleCheckIn(orderInfo)">入住</el-button>
            <el-button size="small" @click="handleChangeReservation">预定变更</el-button>
            <el-button size="small" @click="cancellation(orderInfo)">作废</el-button>
          </el-col>
          <!-- 订单状态:已入住 -->
          <el-col v-if="orderInfo.orderState === '7'">
            <el-button size="small" @click="surrenderHandel(orderInfo)">退租</el-button>
            <el-button size="small" @click="reletHandel(orderInfo)"
            >续租
            </el-button>
            <el-button size="small" @click="handleChangeHouse(orderInfo)">换房
            </el-button>
            <el-button size="small" @click="subletHandel(orderInfo)">转租</el-button>
          </el-col>
          <!-- 订单状态:9退租中、14超时退租中 -->
          <el-col v-if="orderInfo.orderState === '9'||orderInfo.orderState === '14'">
            <el-button size="small" @click="handleCheck(orderInfo)">验房</el-button>
          </el-col>

        </el-row>
        <el-row v-if="!orderId">
          <el-col>
            <el-button size="small" @click="handleReservation">预定</el-button>
            <el-button size="small" @click="handleAddContract">添加合同</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="drawer-footer" v-if="activeName === 'second'">
        <el-row>
          <el-col>
            <el-button size="small" @click="addMemberHandel" v-if="orderInfo.orderState === '7'">添加入住人</el-button>
          </el-col>
        </el-row>
      </div>
    </el-drawer>

    <!--  合同信息  -->
    <ContractInfo v-model="contractInfoVisible" title="合同信息" :data="form" @success="handleSuccess"/>
    <!--  入住  -->
    <CheckIn v-model="checkInOption.visible" :title="checkInOption.title" :data="form" @success="handleSuccess"/>
    <!--  预定变更  -->
    <OrderAdd v-model="changeReservationVisible" :orderId="orderId" @success="handleSuccess" title="预定变更"/>
    <!-- 退租 -->
    <OrderSurrender v-model="surrenderDialogVisible" :orderId="orderId" @success="handleSuccess"/>
    <!--  续租  -->
    <Relet v-model="openRelet" :orderId="orderId" :data="form" @success="handleSuccess"/>
    <!--  换房  -->
    <ChangeHouse v-model="openChangeHouse" :orderId="orderId" @success="handleSuccess" :data="form"/>
    <!-- 转租 -->
    <sublet v-model="openSublet" :orderId="orderId" @success="handleSuccess"/>
    <!-- 验房 -->
    <check-house v-model="openCheck" :orderId="orderId" @success="handleSuccess"></check-house>
    <!-- 同住人操作 -->
    <el-dialog :title="membertitle" :visible.sync="memberVisible" width="500px">
      <el-form :model="perform" ref="perform" label-width="120px">
        <el-form-item label="分类" prop="memberType" :rules="[
          { required: true, message: '请选择分类', trigger: 'blur' },
        ]"
        >
          <el-radio-group v-model="perform.memberType">
            <el-radio label="3">同住人</el-radio>
            <el-radio label="2" :disabled="lessee.memberType === '2'"
                      v-if="orderInfo.orderLessee&&orderInfo.orderLessee.lesseeType ==='2'"
            >房管员
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="姓名" prop="memberName" :rules="[
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ]"
        >
          <el-input v-model="perform.memberName" :disabled="!!perform.memberId && !!perform.facePhoto"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="memberPhone" :rules="[
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3-9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]"
        >
          <el-input v-model="perform.memberPhone" maxlength="11" v-input.int></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard" :rules="[
          { required: true, message: '请输入身份证号', trigger: 'blur' },
        ]"
        >
          <el-input v-model="perform.idCard" :disabled="!!perform.memberId && !!perform.facePhoto"></el-input>
        </el-form-item>
        <el-form-item label="关系" prop="memberRelation" :rules="[
          { required: false, message: '请选择关系', trigger: 'blur' },
        ]" v-if="perform.memberType === '3'"
        >
          <el-select v-model="perform.memberRelation">
            <el-option :label="dict.label" :value="dict.value" v-for="dict in dict.type.member_relation"
                       :key="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件照片" v-if="perform.memberId">
          <!--          <ImageUploadSingle v-model="perform.idCardImgs" ref="idCardImgs" />-->
          <!--          <div class="handle-button" v-if="perform.idCardImgs">-->
          <!--            <el-button type="primary" size="small" @click="handleUpload">更换</el-button>-->
          <!--          </div>-->
          <el-image
            style="width: 100px; height: 100px;background-color: #f0f2f5;text-align: center;line-height: 100px;color: #9292A7;font-size: 24px;margin-right: 10px;"
            :src="perform.facePhoto"
            fit="contain"
            :preview-src-list="[perform.facePhoto]"
            v-if="perform.facePhoto"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="memberVisible = false">取 消</el-button>
        <el-button type="primary" @click="perSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增预定订单 -->
    <orderAdd v-model="reservationVisible" @success="closeCheck" :is-designated-house="true" :designed-house="house" :title="'新增预定订单'"></orderAdd>
    <!-- 新增租客合同 -->
    <AddLesseeContract v-model="addLesseeContractDialogVisible" title="新增租客合同" @success="closeCheck" :is-designated-house="true" :designed-house="house" />

  </div>
</template>

<script>
import { getDayOrWeek, inTime, DateDiff } from '@/utils/common/time'
import {
  houseDynamic,
  checkIn,
  cancelReservation,
  exchangeHouse,
  relet,
  checkingOut,
  memberList,
  memberAdd,
  memberPut,
  memberDel
} from '@/api/house/condition'
import SelectHouse from '@/views/house/condition/components/select-house.vue'
import { debounce } from '@/utils'
import { compareDate, compareDateTime } from '@/utils/common/moment'
import ContractInfo from '@/views/long-short-rent/order/component/contract-info.vue'
import CheckIn from '@/views/long-short-rent/order/component/check-in.vue'
import OrderAdd from '@/views/long-short-rent/order/component/order-add.vue'
import { cancelOrder } from '@/api/order/order'
import OrderSurrender from '@/views/long-short-rent/order/component/order-surrender.vue'
import Relet from '@/views/long-short-rent/order/component/relet.vue'
import ChangeHouse from '@/views/long-short-rent/order/component/change-house.vue'
import sublet from '@/views/long-short-rent/order/component/sublet.vue'
import checkHouse from '@/views/long-short-rent/order/component/check-house.vue'
import { getRoom } from '@/api/house/room'
import AddLesseeContract from '@/views/long-short-rent/contract/lessee/components/add.vue'

export default {
  name: 'long-short-rent',
  components: { AddLesseeContract, checkHouse, sublet, ChangeHouse, Relet, OrderSurrender, OrderAdd, CheckIn, ContractInfo, SelectHouse },
  dicts: ['cancel_reservation', 'order_all_state', 'order_type', 'order_source', 'trading_mode', 'member_relation'],
  props: {
    value: {
      type: Boolean,
      default: false
    },
    orderId: {
      default: ''
    },
    orderType: {
      default: ''
    },
    houseId: {
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      activeName: 'first',
      house: {},
      orderInfo: {},
      lessee: {},
      list: [],
      // 合同信息弹窗
      contractInfoVisible: false,
      // 预定变更弹窗
      changeReservationVisible: false,
      // 退租弹窗
      surrenderDialogVisible: false,
      // 续租弹窗
      openRelet: false,
      // 换房弹窗
      openChangeHouse: false,
      // 转租弹窗
      openSublet: false,
      // 验房弹窗
      openCheck: false,

      // 同住人操作弹窗
      memberVisible: false,
      membertitle: '添加同住人',
      perform: {
        houseId: '',
        orderId: '',
        memberType: '3',
        memberName: '',
        memberPhone: '',
        memberRelation: '',
        sex: '1',
        idCard: '',
        idCardImgs: '',
        facePhoto: ''
      },

      // 表单
      form: {},
      // 入住选项
      checkInOption: {
        visible: false,
        title: '入住'
      },
      // 新增预定订单
      reservationVisible: false,
      // 新增租客合同
      addLesseeContractDialogVisible: false,
    }
  },
  computed: {
    drawer: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    // 房屋信息
    houseInfo: {
      get() {
        if (this.orderInfo && this.orderInfo.orderId) {
          return this.orderInfo.houseNew ? this.orderInfo.houseNew : this.orderInfo.house
        }
        return {}
      },
      set(v) {
      }
    },
    // 退费类型(1.房费,2.押金,3.损坏赔偿,4.延迟退房费)
    orderRefundItemByRefundType() {
      return (type) => {
        let orderRefundItemList = this.orderInfo.orderRefundItemList
        if (orderRefundItemList && orderRefundItemList.length) {
          let Item = orderRefundItemList.find(item => item.refundType == type)
          return Item ? Item.itemSum : 0
        }
        return ''

      }
    },
    // 是否展示入住人员
    showMember: {
      get() {
        return this.orderInfo.orderState && ['7', '8', '9', '10', '11', '12', '13', '14', '15'].includes(this.orderInfo.orderState)
      },
      set() {
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.init()
        }
      },
      immediate: true
    }
  },
  methods: {
    DateDiff: DateDiff,
    closeCheck() {
      this.$emit('success')
      this.drawer = false
    },
    init() {
      this.reset()
      this.getOrderinfo()
    },
    reset() {
      this.activeName = 'first'
      this.orderInfo = ''
      this.lessee = {}
      this.list = []
    },
    // 获取订单信息
    getOrderinfo() {
      if (this.orderId) {
        this.loading = true
        houseDynamic(this.orderId).then((res) => {
          this.orderInfo = res.data
          if (this.showMember) {
            this.getperList()
          }
          // this.getperList()
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.getHouseInfo()
      }

    },
    // 获取同住人列表
    getperList() {
      console.log('getPerList')
      this.lessee = {}
      let params = {
        orderId: this.orderInfo.orderId,
        houseId: this.orderInfo.houseId
      }
      memberList(params).then((res) => {
        let list = res.rows
        let lessee = {}

        if (this.orderInfo.orderLessee.lesseeType === '2') {
          // 承租为企业时，取出房管家信息
          lessee = list.filter((item) => item.memberType === '2')
          // 取出其他同住人信息
          this.list = list.filter((item) => item.memberType !== '2')
        } else if (this.orderInfo.orderLessee.lesseeType === '1') {
          //承租为个人时，取出承租人信息
          lessee = list.filter((item) => item.memberType === '1')
          // 取出其他同住人信息
          this.list = list.filter((item) => item.memberType !== '1')
        }
        this.lessee = lessee[0] ? lessee[0] : {}
      })
    },

    //新增
    addMemberHandel() {
      this.membertitle = '添加入住人'
      this.perform = this.$options.data().perform
      this.memberVisible = true
    },
    //编辑同住人
    putMember(row) {
      this.membertitle = '编辑同住人'
      this.perform = JSON.parse(JSON.stringify(row))
      this.memberVisible = true
    },
    //新增/编辑同住人
    perSubmit() {
      this.perform.orderId = this.orderInfo.orderId
      this.perform.houseId = this.orderInfo.houseId
      const getSex = (no = '') => {
        if (!no) return no
        const toStr = no.toString()
        if (toStr.length < 17) return no
        return Number(toStr.substring(16, 17)) % 2 ? '1' : '2' //1男 2女
      }
      this.$refs['perform'].validate((valid) => {
        if (valid) {
          if (this.perform.memberId) {
            memberPut(this.perform).then((res) => {
              this.$modal.msgSuccess(res.msg || '编辑成功')
              this.getperList()
              this.memberVisible = false
            })
          } else {
            this.perform.sex = getSex(this.perform.idCard)
            memberAdd(this.perform).then((res) => {
              this.$modal.msgSuccess(res.msg || '新增成功')
              this.getperList()
              this.memberVisible = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除同住人
    delMember(row) {
      this.$confirm('确认删除入住人？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        memberDel(row.memberId).then((res) => {
          this.$message({
            type: 'success',
            message: res.msg || '删除成功!'
          })
          this.getperList()
        })
      })
    },

    //公共操作成功回调
    handleSuccess(res) {
      this.form = {}
      this.getOrderinfo()
      this.$emit('success')
    },
    // 合同信息
    handleContractInfo() {
      this.form = { ...this.orderInfo, cooperationType: this.orderInfo.house.cooperationType }
      this.contractInfoVisible = true
    },
    // 入住
    handleCheckIn(row) {
      if (row.contractSignFlag == 0) {
        this.$confirm('房间未完成合同签署，确认继续入住?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          this.checkInOption.visible = true
          this.checkInOption.title = '入住'
          this.form = { ...row }
        }).catch((err) => {
          console.log(err)
        })
      } else {
        this.checkInOption.visible = true
        this.checkInOption.title = '入住'
        this.form = { ...row }
      }
    },
    //验房
    handleCheck(row) {
      this.orderId = row.orderId
      this.openCheck = true
    },
    // 预定变更
    handleChangeReservation() {
      this.changeReservationVisible = true
      this.form = { ...this.orderInfo }
    },
    // 作废
    cancellation(row) {
      this.$confirm('作废后无法恢复，请谨慎操作  ', '确定订单作废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          cancelOrder(row.orderId).then((response) => {
            this.$message.success(response.msg || '操作成功')
            this.handleSuccess()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    // 退租
    surrenderHandel(row) {
      this.orderId = row.orderId
      this.surrenderDialogVisible = true
    },
    // 续租
    reletHandel(row) {
      this.orderId = row.orderId
      this.form = { ...row }
      this.openRelet = true
    },
    //换房操作
    handleChangeHouse(row) {
      this.orderId = row.orderId
      this.form = { ...row }
      this.openChangeHouse = true
    },
    //转租操作
    subletHandel(row) {
      this.orderId = row.orderId
      this.openSublet = true
    },
    handleUpload() {
      this.$refs.idCardImgs.$el.querySelector('input[type="file"]').click()
    },
    // 获取房屋信息
    getHouseInfo() {
      getRoom(this.houseId).then((response) => {
        this.house = response.data
      })
    },
    // 预定
    handleReservation() {
      this.reservationVisible = true
    },
    // 添加合同
    handleAddContract() {
      this.addLesseeContractDialogVisible = true
    }

  }

}
</script>

<style lang="scss" scoped>
.member-title {
  color: #303133;
  font-size: 16px;
  font-weight: bold;
}

.member-box {
  border: 1px solid #666;
  border-radius: 4px;
  padding: 20px;
  margin: 20px 0;
  color: #606266;
  line-height: 1.5;
  font-size: 14px;
}

.query-button {
  margin-bottom: 30px;
}

.drawer-footer {
  background: #fff;
  bottom: 0;
  position: absolute;
  width: 100%;
  height: 80px;
  padding: 10px 30px;
}
</style>
